var mysql = require("mysql");
var crypto = require('crypto');
const log4js = require('log4js');
const logger = log4js.getLogger('db');
var pool = null;

function nop(a, b, c, d, e, f, g) {

}

function query(sql, callback, keepConn) {
    pool.getConnection(function (err, conn) {
        if (err) {
            callback(err, null, null);
        } else {
            try {
                conn.query(sql, function (qerr, vals, fields) {
                    //释放连接

                    if (!keepConn) {
                        conn.release();
                    }

                    //事件驱动回调  
                    callback(qerr, vals, fields);
                });
            }
            catch (e) {
                logger.error(e);
            }
        }
    });
};

exports.init = function (config) {
    pool = mysql.createPool({
        host: config.HOST,
        user: config.USER,
        password: config.PSWD,
        port: config.PORT,
        database: config.DB,
    });
};

exports.isUserExist = function (account, callback) {
    callback = callback == null ? nop : callback;
    if (account == null) {
        callback(false);
        return;
    }

    var sql = 'SELECT * FROM t_users WHERE account = "' + account + '"';
    query(sql, function (err, rows, fields) {
        if (err) {
            throw err;
        }

        if (rows.length == 0) {
            callback(false);
            return;
        }

        callback(true, rows[0]);
    });
}

exports.getUserCards = function (account, callback) {
    callback = callback == null ? nop : callback;
    if (account == null) {
        callback(false);
        return;
    }

    var sql = 'SELECT * FROM t_cards WHERE owner = "' + account + '"';
    query(sql, function (err, rows, fields) {
        if (err) {
            throw err;
        }

        if (rows.length == 0) {
            callback(false);
            return;
        }

        callback(true, rows);
    });
}

exports.getUserByAccounts = function (accounts, callback) {
    callback = callback == null ? nop : callback;
    if (accounts == null) {
        callback(false);
        return;
    }

    var string = ''
    for (var i = 0; i < accounts.length; i++) {
        string = string + '"' + accounts[i] + '"';
        if (i != accounts.length - 1) {
            string = string + ',';
        }
    }

    var sql = 'SELECT * FROM t_users WHERE account in (' + string + ')';
    query(sql, function (err, rows, fields) {
        if (err) {
            throw err;
        }

        if (rows.length == 0) {
            callback(false);
            return;
        }

        callback(true, rows);
    });
}

exports.createUser = function (account, name, callback) {
    callback = callback == null ? nop : callback;
    if (account == null || name == null) {
        callback(false);
        return;
    }

    this.addCardsToUser([1, 1, 1, 2, 2, 2], account, function(succeed, data){

        var cards = [];
        for(var i = 0; i < data.length; i++){
            cards.push(data[i].id);
        }

        var cardgroups = [{
            id: 0,
            name: '默认卡组',
            cards: cards
        }];
        
        var sql = 'INSERT INTO t_users(account,name,cards,cardgroups) VALUES("{0}","{1}",\'{2}\',\'{3}\')';
        sql = sql.format(account, name, null, JSON.stringify(cardgroups));

        query(sql, function (err, rows, fields) {
            if (err) {
                throw err;
            }

            var msg = {
                id: rows.insertId,
                account: account,
                name: name,
                cardgroups: JSON.stringify(cardgroups),
            }
            callback(true, msg);
        });

    }, true);
};

exports.addCardsToUser = function (dbids, account, callback, keepConn) {
    callback = callback == null ? nop : callback;
    if (account == null || dbids == null) {
        callback(false);
        return;
    }

    var sql = 'INSERT INTO t_cards( dbid, owner ) VALUES';
    for (var i = 0; i < dbids.length; i++) {
        if (i < dbids.length - 1) {
            sql = sql + '({}, "{}"),'.format(dbids[i], account);
        }
        else {
            sql = sql + '({}, "{}")'.format(dbids[i], account);
        }
    }

    query(sql, function (err, rows, fields) {
        if (err) {
            throw err;
        }

        var startid = rows.insertId;
        var data = [];
        for (var i = 0; i < dbids.length; i++) {
            var card = {
                id: startid + i,
                dbid: dbids[i],
                owner: account,
            }
            data.push(card)
        }

        callback(true, data);
    }, keepConn);
};